import React, { useCallback, useMemo, useState } from "react";
import Test from "./Test";
import ButtonCom from "./ButtonCom";

export default function MemoCom() {
  //声明一个状态
  let [count, setCount] = useState(100);
  let [arr, setArr] = useState([1,2,3,4,10,23,26,28,466,233]);

  //声明事件函数  缓存一个函数
  let fn = useCallback(() => {
    setCount((count) => count + 1);
    // setCount(count + 1);
  }, []);

  // useMemo 用来缓存一个函数的运行结果.
  let data = useMemo(() => {
    console.log('memo run')
    let result = 1;
    arr.forEach(item => {
      result *= item;
    });
    return result;
  }, [arr]);

  return (
    <>
      <h2>MemoCom</h2>
      <h4>{count}</h4>
      <ButtonCom
        onClick={fn}
      />
      <hr />
      <Test />
      <hr />
      <h4>{data}</h4>
      <button onClick={() => {
        setArr([...arr, 2]);
      }}>*2</button>
    </>
  );
}
